﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Data;

namespace ImportOrders
{
    /// <summary>
    /// Interaction logic for dlgViewFile.xaml
    /// </summary>
    public partial class dlgViewFile : Window
    {
        private StreamReader _srInput = null;
        private string _templateFile = null;
        private string _fileName = null;
        private DataTable _dt = null;

        public dlgViewFile(string fileName, string templateFile)
        {
            InitializeComponent();
            List<List<string>> lines = new List<List<string>>();

            string strLine;
            int i;

            _templateFile = templateFile;
            _fileName = fileName;

            try
            {
                try
                {
                    _srInput = new StreamReader(fileName);
                }
                catch (System.Exception err)
                {
                    throw new Exception("Missing import file " + fileName + "\n" + err.Message);
                }

                if (templateFile == null)
                    // Read the header line.
                    strLine = _srInput.ReadLine();
                else
                {
                    StreamReader srTemplateInput;
                    try
                    {
                        srTemplateInput = new StreamReader(templateFile);
                    }
                    catch (System.Exception)
                    {
                        throw new Exception("Missing template file " + templateFile);
                    }
                    // Read the header line.
                    strLine = srTemplateInput.ReadLine();
                    srTemplateInput.Close();
                }
                if (strLine == null)
                    return;
                if (strLine.Trim().Length == 0)
                    return;


                TokenString tokens = new TokenString(strLine, null, true);

                while (true)
                {
                    List<string> line = new List<string>();
                    // Test the validity of the header names
                    for (i = 0; i < tokens.TokenCount; i++)
                    {
                        line.Add(tokens[i]);
                    }
                    lines.Add(line);

                    if ((strLine = _srInput.ReadLine()) == null)
                        break;
                    tokens = new TokenString(strLine, nextLine, true);
                }
            }
            finally
            {
                if (_srInput != null)
                    _srInput.Close();
            }

            // Move the lines into a datatable
            int maxItems = 0;
            foreach (List<string> line in lines)
                if (line.Count > maxItems)
                    maxItems = line.Count;

            _dt = new DataTable();
            _dt.Columns.Add(new DataColumn("Line", System.Type.GetType("System.Int32")));
            for (i = 0; i < maxItems; i++)
            {
                if (i < lines[0].Count)
                    _dt.Columns.Add(new DataColumn(lines[0][i], System.Type.GetType("System.String")));
                else
                    _dt.Columns.Add(new DataColumn("Column " + i.ToString(), System.Type.GetType("System.String")));
            }
            for (i = 1; i < lines.Count; i++)
            {
                DataRow dr = _dt.NewRow();
                dr[0] = i;
                for (int j = 0; j < lines[i].Count; j++)
                    dr[j+1] = lines[i][j];
                _dt.Rows.Add(dr);
            }

            ((CollectionViewSource)FindResource("Lines")).Source = _dt;
        }

        public string nextLine()
        {
            return _srInput.ReadLine();
        }

        private void gridLines_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Column.Header.ToString() == "Line")
                e.Column.IsReadOnly = true;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StreamWriter sw = new StreamWriter(_fileName);

                if (_templateFile != null)
                {
                    for (int i = 0; i < _dt.Columns.Count; i++)
                    {
                        sw.Write(_dt.Columns[i].ColumnName);
                        if (i + 1 < _dt.Columns.Count)
                            sw.Write(",");
                    }
                    sw.Write("\n");
                }

                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    for (int j = 1; j < _dt.Columns.Count; j++)
                    {
                        string value = (string)_dt.Rows[i][j];
                        if (value.Contains(',') || value.Contains('\t') || value.Contains("\n") || value.Contains("\r"))
                            value = "\"" + value.Replace("\"", "\"\"") + "\"";
                        sw.Write(value);
                        if (j + 1 < _dt.Columns.Count)
                            sw.Write(",");
                    }
                    if (i+1 < _dt.Rows.Count)
                        sw.Write("\n");
                }
                sw.Close();
                Close();
            }
            catch (Exception err)
            {
                MessageBox.Show("Error writing to file\n" + err.Message);
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void mnuDeleteCell_Click(object sender, RoutedEventArgs e)
        {
            Point menuClickPoint = ((sender as FrameworkElement).Parent as ContextMenu).TranslatePoint(new Point(0, 0), gridLines);

            // get the first potential treeView object that was hit   
            DependencyObject obj = gridLines.InputHitTest(menuClickPoint) as DependencyObject;
            if (!(obj is DataGridCell))
                obj = ((FrameworkElement)obj).Parent;
            if (obj is DataGridCell)
            {
                DataGridCell cell = (DataGridCell)obj;

                DataRow dr = ((DataRowView)((CollectionViewSource)FindResource("Lines")).View.CurrentItem).Row;
                for (int i = cell.Column.DisplayIndex; i < _dt.Columns.Count-1; i++)
                    dr[i] = dr[i + 1];
                dr[_dt.Columns.Count - 1] = DBNull.Value;
            }
        }

        private void mnuInsertCell_Click(object sender, RoutedEventArgs e)
        {
            Point menuClickPoint = ((sender as FrameworkElement).Parent as ContextMenu).TranslatePoint(new Point(0, 0), gridLines);

            // get the first potential treeView object that was hit   
            DependencyObject obj = gridLines.InputHitTest(menuClickPoint) as DependencyObject;
            if (!(obj is DataGridCell))
                obj = ((FrameworkElement)obj).Parent;
            if (obj is DataGridCell)
            {
                DataGridCell cell = (DataGridCell)obj;

                DataRow dr = ((DataRowView)((CollectionViewSource)FindResource("Lines")).View.CurrentItem).Row;
                for (int i = _dt.Columns.Count - 1; i > cell.Column.DisplayIndex; i--)
                    dr[i] = dr[i - 1];
                dr[cell.Column.DisplayIndex] = DBNull.Value;
            }
        }

        private void mnuDeleteColumn_Click(object sender, RoutedEventArgs e)
        {
            Point menuClickPoint = ((sender as FrameworkElement).Parent as ContextMenu).TranslatePoint(new Point(0, 0), gridLines);

            // get the first potential treeView object that was hit   
            DependencyObject obj = gridLines.InputHitTest(menuClickPoint) as DependencyObject;
            if (!(obj is DataGridCell))
                obj = ((FrameworkElement)obj).Parent;
            if (obj is DataGridCell)
            {
                DataGridCell cell = (DataGridCell)obj;
                _dt.Columns.RemoveAt(cell.Column.DisplayIndex);

                ((CollectionViewSource)FindResource("Lines")).Source = null;
                ((CollectionViewSource)FindResource("Lines")).Source = _dt;
            }
        }
    }
}
